import React from 'react';

import FormCommon from '@/components/FormCommon';
import CommonTable from '@/components/commonTable';
import { IFilterParams } from '@/components/commonTable/interface';
import { add, deleted, getCurrent, update } from '@/services/api/order';
import { PageContainer } from '@ant-design/pro-components';
import { history, useModel } from '@umijs/max';
import { useRequest } from 'ahooks-v3';
import { Popconfirm, Select, Space, message } from 'antd';
import { useForm } from 'antd/es/form/Form';

export interface IOrderProps {
	[key: string]: any;
}

const FILTER_CONDITION: IFilterParams = {
	keywords: '',
	currentPage: 1,
	pageSize: 10,
};
const Order: React.FC<IOrderProps> = () => {
	// 获取当前用户的身份信息
	const { initialState = {} } = useModel('@@initialState');
	const {
		userInfo: { city },
	} = initialState || {};

	const [isVisible, setIsVisible] = React.useState<boolean>(false); // 用于展示新增 modal 框的展示
	const [form] = useForm();
	const {
		loading,
		data,
		run: getListRun,
	} = useRequest((params) => getCurrent(params), {
		manual: true,
	});

	const [filterCondition, setFilterCondition] = React.useState<IFilterParams>(
		FILTER_CONDITION || {
			keywords: '',
			currentPage: 1,
			pageSize: 10,
		},
	);

	// 点击新增按钮
	const onHandleAdd = () => {
		form.resetFields();
		setIsVisible(true);
	};

	// 批量删除
	const onDelete = async (rowKeys: React.Key[], rows: Record<string, any>[]) => {
		try {
			const res = await deleted(rowKeys as number[]);
			if (res.status !== 200) {
				return message.error(res.message || '删除失败');
			}
			message.success('删除成功');
		} catch (error) {
			console.log('error', error);
		} finally {
			setFilterCondition({ ...FILTER_CONDITION });
		}
	};

	React.useEffect(() => {
		getListRun({ ...filterCondition, city });
	}, [filterCondition, city, getListRun]);

	// 页面table的数据
	const columns = [
		{
			title: '使用该服务的用户',
			key: 'user',
			dataIndex: 'user',
			render: (user, _) => {
				return (
					<div>
						{user?.name || '_'} <span>{user?.role}</span>
					</div>
				);
			},
		},
		{
			title: '服务类型',
			key: 'service',
			dataIndex: 'service',
			render: (service, _) => {
				return (
					<div>
						<span>{service?.category || '-'}</span>
					</div>
				);
			},
		},
		{
			title: '使用该服务的车辆',
			key: 'car',
			dataIndex: 'car',
			render: (car, _) => {
				return (
					<div>
						{car?.brand || '_'} <span>{car?.shape}</span>
					</div>
				);
			},
		},
		{
			title: '订单状态',
			width: 200,
			key: 'order_status',
			dataIndex: 'order_status',
			render: (order_status: any, record: any) => {
				return (
					<div>
						<Select
							defaultValue={order_status}
							style={{ width: 120 }}
							onChange={async (val) => {
								const res = await update(record.id, {
									order_status: val,
								});
								if (res.status !== 200 || res.data.code === '901') {
									return message.error(res.message || '修改失败');
								}
								message.success('修改成功');
								setFilterCondition({ ...FILTER_CONDITION });
							}}
						>
							<Select.Option value="0">待处理</Select.Option>
							<Select.Option value="1">进行中</Select.Option>
							<Select.Option value="2">已完成</Select.Option>
							<Select.Option value="3">已完结</Select.Option>
						</Select>
					</div>
				);
			},
		},
		{
			title: '操作',
			key: 'operator',
			render: (_, record: any) => {
				return (
					<Space size="middle">
						<a
							onClick={() => {
								history.push('/detail/' + record.id, record.type || 'user');
							}}
						>
							详情
						</a>
						<Popconfirm
							title="删除"
							description="删除后不可恢复，是否确定删除?"
							placement="topRight"
							onConfirm={async () => {
								const res = await deleted([record.id]);
								if (res.status !== 200) {
									return message.error(res.message || '删除失败');
								}
								message.success('删除成功');
								setFilterCondition({ ...FILTER_CONDITION });
							}}
							okText="确定"
							cancelText="取消"
						>
							<a style={{ color: 'red' }}>删除</a>
						</Popconfirm>
					</Space>
				);
			},
		},
	];

	// 添加的表单项
	const editFormItems = [
		{
			title: '服务',
			dataIndex: 'serviceId',
			valueType: 'digit',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '用户',
			dataIndex: 'userId',
			valueType: 'digit',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
		{
			title: '车辆',
			dataIndex: 'carId',
			valueType: 'digit',
			width: 'm',
			formItemProps: {
				rules: [
					{
						required: true,
						message: '此项为必填项',
					},
				],
			},
		},
	];

	return (
		<div>
			<PageContainer>
				<CommonTable
					isAdd={false}
					isSticky
					loading={loading}
					columns={columns}
					total={data?.data?.total}
					dataSource={data?.data?.list}
					filterCondition={filterCondition}
					setFilter={setFilterCondition}
					isPagination={data?.total}
					onDelete={onDelete}
					isRowSelection
					onAdd={onHandleAdd}
				/>
			</PageContainer>

			{/* 弹窗 */}
			<FormCommon
				isOpen={isVisible}
				title="新增订单记录"
				layoutFormType="ModalForm"
				layout="horizontal"
				formInstance={form}
				setIsOpen={setIsVisible}
				width={400}
				onChange={async (values) => {
					const res = await add(values);
					if (res.status !== 200) {
						return message.error(res.message || '新增失败');
					}
					message.success('新增成功');
					setFilterCondition({ ...FILTER_CONDITION });
					setIsVisible(false);
				}}
				formColumn={editFormItems}
			/>
		</div>
	);
};

export default Order;
